<template>
<div class="container">
    <img :src="img" alt="" id="image">
    <div class="toolbar">
        <span @click="$emit('close')">取消</span>
        <span @click="onConfirm">完成</span>
    </div>
</div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: String,
      required: true
    }
  },
  mounted () {
    // 不是非得要用ref来获取dom
    // ref和id没什么区别 只不过ref更强大，ref不但可以拿DOM，还可以拿组件
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
      zoomable: false,
      highlight: false,
      guides: false
    })
  },
  data () {
    return {
      cropper: null
    }
  },
  methods: {
    onConfirm () {
      this.$toast.loading({
        message: '更新中....',
        overlay: true
      })
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // console.log(blob)
        var fd = new FormData()
        fd.append('photo', blob)
        try {
          const { data: res } = await updateUserPhoto(fd)
          console.log(res)
          // 关闭弹出层
          this.$emit('close')
          this.$emit('update-photo', res.data.photo)
          this.$toast.success('更新头像成功')
        } catch (err) {
          this.$toast.fail('更新头像失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
img {
    max-width: 100%;
}

.container {
    background: #000;
    height: 100vh;

    .toolbar {
        height: 90px;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;
        padding: 0 20px;

        span {
            width: 90px;
            height: 90px;
            font-size: 30px;
            color: #fff;
            display: inline-block;
            text-align: center;
            line-height: 90px;
        }
    }
}
</style>
